import Vue from 'vue'
import Vuex from 'vuex'
import { getToken, setToken } from '../untils/storage.js'
import { getUserProfil, setUserProfil } from '../untils/profil.js'

Vue.use(Vuex)

const tokenObj = getToken() || {} // 如果值为null则是空对象，因为null.xx会报错，而对象.xx没有值为undefined
const initUserInfo = getUserProfil() || {}
export default new Vuex.Store({
  state: {
    tokenInfo: {
      token: tokenObj.token || '', // 如果没有值则为空
      refresh_token: tokenObj.refresh_token || ''
    }
  },
  mutations: {
    mSetTokenInfo (state, newTokenInfo) {
      state.tokenInfo = newTokenInfo
      setToken(newTokenInfo)
    }
  },
  getters: {
    isLogin (state) {
      return !!state.tokenInfo.token
    }
  },
  actions: {
  },
  modules: {
    userInfo: {
      namespaced: true,
      state: {
        birthday: initUserInfo.birthday || '',
        gender: initUserInfo.gender || '',
        id: initUserInfo.id || '',
        mobile: initUserInfo.mobile || '',
        name: initUserInfo.name || '',
        photo: initUserInfo.photo || ''
      },
      mutations: {
        msetUserInfo (state, newUserInfo) {
          state.birthday = newUserInfo.birthday
          state.gender = newUserInfo.gender
          state.id = newUserInfo.id
          state.mobile = newUserInfo.mobile
          state.name = newUserInfo.name
          state.photo = newUserInfo.photo
          setUserProfil(newUserInfo)
        },
        // 更新用户姓名并进行持久化
        mUpdateUserName (state, newName) {
          state.name = newName
          const { name, photo, birthday, gender, mobile, id } = state
          setUserProfil({ name, photo, birthday, gender, mobile, id })
        },
        mUpdateUserGender (state, newGender) {
          state.gender = newGender // 1、修改vuex中的性别信息
          const { name, photo, birthday, gender, mobile, id } = state // 2、解构state数据
          setUserProfil({ name, photo, birthday, gender, mobile, id }) // 3、把更新后的信息重新进行持久化保存
        },
        mUpdateUserBirthday (state, newBirthday) {
          state.birthday = newBirthday
          const { name, photo, birthday, gender, mobile, id } = state
          setUserProfil({ name, photo, birthday, gender, mobile, id })
        },
        mUpdateUserPhoto (state, newPhoto) {
          state.photo = newPhoto
          setUserProfil(state)
        }
      }
    }
  }
})
